package dproxy.server.common.util;

/**
 * Utility methods to convert objects.
 */
public final class UtilConvert {

    /**
     * Private constructor to avoid instantiation.
     */
    private UtilConvert() {
        
    }
    
    /**
     * Convert a byte array to string representation.
     * @param byteArray Byte array
     * @return String representation
     */
    public static String convertToString(byte [] byteArray) {
        StringBuffer buffer = new StringBuffer();
        
        for (int i = 0; i < byteArray.length; i++) {
            buffer.append((char)byteArray[i]);
        }
        
        return buffer.toString();
    }
    
    /**
     * Convert a byte array to string representation.
     * @param byteArray Byte array
     * @param maxLen Limit size of string
     * @return String representation
     */
    public static String convertToString(byte [] byteArray, int maxLen) {
        StringBuffer buffer = new StringBuffer();
        if (maxLen > byteArray.length) {
            maxLen = byteArray.length;
        }
        // Transform the N first bytes of the request on a string
        for (int i = 0; i < maxLen; i++) {
            buffer.append((char)byteArray[i]);
        }
        return buffer.toString();
    }
    
    /**
     * Convert a byte array to string representation to be shown to user.
     * @param byteArray Byte array
     * @param maxLen Limit size of string
     * @return String representation
     */
    public static String convertToDisplay(byte [] byteArray, int maxLen) {
        StringBuffer buffer = new StringBuffer();
        if (maxLen > byteArray.length) {
            maxLen = byteArray.length;
        }
        // Transform the N first bytes of the request on a string
        for (int i = 0; i < maxLen; i++) {
            char character = (char)byteArray[i];
            character = getPrintableCharacter(character);
            buffer.append(character);
        }
        return buffer.toString();
    }

    /**
     * Replaces control characters for "pretty printing".
     * @param character input
     * @return filtered character
     */
    private static char getPrintableCharacter(char character) {
        int type = Character.getType(character);
            
        if (type == Character.CONTROL 
             || type == Character.SPACE_SEPARATOR) {
            character = ' ';
        }
        return character;
    }
    
}
